#! /usr/bin/env python
"""
::BOH
$Id: alertables.py,v 1.9 2006/04/26 02:49:00

Copyright (c) 2006 George Bobeck. All rights reserved.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
::EOH

Configures custom alert values for alerting.
"""
"""
TODO LIST:
    For simple mode, make temperature scale selectable 
    (convert to/from C as necessary)
    
    For advanced mode, double check everything everything
"""
import MySQLdb
import sys
import os

def clearscreen(numlines=100):
    """Clear the console.

    numlines is an optional argument used only as a fall-back.
    """
    
    if os.name == "posix":
        # Unix/Linux/MacOS/BSD/etc
        os.system('clear')
    elif os.name in ("nt", "dos", "ce"):
        # DOS/Windows
        os.system('CLS')
    else:
        # Fallback for other operating systems.
        print '\n' * numlines 

def prompt(prompt):
    return raw_input(prompt).strip()
    
def conf(location):
    f = open(location,'r')
    a = f.readlines()
    fl = []
    var_list = []
    for e in a:
        if "#" not in e:
            e = e.strip('\n')
            e = e.strip('\r')
            if e == '':
                pass
            else:
                e = e.split("\t")
                try:
                    e.remove('')
                except:
                    pass
            var_list.extend(e)
    return var_list
global verbose

confs = conf(sys.argv[ 1 ])
verbose = bool(confs[confs.index("verbose")+1])
dbhost = confs[confs.index("dbhost")+1]
dbport = int(confs[confs.index("dbport")+1])
dbuser = confs[confs.index("dbuser")+1]
dbpasswd = confs[confs.index("dbpasswd")+1]
dbase = confs[confs.index("dbase")+1]


clearscreen()
if verbose:
    print "Connecting, using these values:"
    print "Host: ",dbhost
    print "Port: ",dbport
    print "User: ",dbuser
    print "(Password Not Printed)"
    print "Database: ",dbase
    prompt("Press any key to continue...")

def dbconnect():
    global ms
    ms = MySQLdb.connect(host = dbhost,port = dbport ,user = dbuser,passwd=dbpasswd,db=dbase)
    global cur
    cur = ms.cursor()

dbconnect()
global cur
cur.execute("""select sid from sensors""")
x = cur.fetchall()
x = list(x)
if x == []:
    print "Database contains no Sensors...  I've got nothing to do, exiting."
    global ms
    ms.close()
    sys.exit(1)
else:
    sensors = []
    while x:
        i = x.pop()
        sensors.append(i[0])
    sensors.sort()

while 1:
    mode = prompt("USE 'simple' or 'advanced' mode, or exit?  ")
    if mode.lower() == "yes":
        print "Pick One!"
    elif mode.lower() == "s":
        mode = "simple"
        break
    elif mode.lower() == "simple":
        mode = "simple"
        break            
    elif mode.lower() == "a":
        mode = "advanced"
        break
    elif mode.lower() == "advanced":
        mode = "advanced"
        break
    elif mode.lower() == "e":
        clearscreen()
        print "Alertables Exiting"
        sys.exit(0)
    elif mode.lower() == "exit":
        clearscreen()
        print "Alertables Exiting"
        sys.exit(0)        
    else:
        print "Invalid Option!"

clearscreen()
while 1:
    if mode == "simple":
        option = 0
        while option == 0:
            print "Options:"
            print "(1) List Sensors Only"
            print "(2) List Alertables"
            print "(3) Create Alertable"
            print "(4) Delete Alertable"
            print "(5) EXIT"
            option = prompt("Choose an option:  ")
            options = ["1","2","3","4","5"]
            if option not in options:
                print "Option Not Available!"
                option = 0
                prompt("Press any key to continue...")
                clearscreen()

        if option == "5":
            clearscreen()
            global ms
            try:
                ms.close()
                print "Connection to DB has been closed"
            except:
                pass
            print "Alertables Exiting"
            sys.exit(0)

        if option == "1" or option == "3":
            print "Sensors:"
            l = 0
            for i in sensors:
                print str(l) + ") " + i
                l = l + 1
            del l
            if option == "3":
                    ald = -1
                    while ald == -1:
                        ald = prompt("Enter the number of Sensor to become alertable: ")
                        try:
                            ald = int(ald)
                            if ald >= (len(sensors)):
                                ald = -1
                                print "Invalid number."
                        except:
                            print "Invalid Entry."
                            ald = -1
                    min_t = prompt("Minimum Temperature (C), * for default: ")
                    if min_t == "*":
                        min_t = "5"
                    max_t = prompt("Maximum Temperature (C), * for default: ")
                    if max_t == "*":
                        max_t = "35"
                    min_h = prompt("Minimum Humidity, * for default: ")
                    if min_h == "*":
                        min_h = "10"                                        
                    max_h = prompt("Maximum Humidity, * for default: ")
                    if max_h == "*":
                        max_h = "85"
                    min_v1 = prompt("Minimum v1, * for default: ")
                    if min_v1 == "*":
                        min_v1 = "0"
                    max_v1 = prompt("Maximum v1, * for default: ")
                    if max_v1 == "*":
                        max_v1 = "0"
                    min_v2 = prompt("Minimum v2, * for default: ")
                    if min_v2 == "*":
                        min_v2 = "0"
                    max_v2 = prompt("Maximum v2, * for default: ")
                    if max_v2 == "*":
                        max_v2 = "0"
                    cur.execute("""insert ignore into alertables values(%s,%s,%s,%s,%s,%s,%s,%s,%s)on duplicate key update temp_min = %s, temp_max = %s, humid_min = %s, humid_max = %s, v1_min = %s, v1_max = %s, v2_min = %s, v2_max = %s """,(sensors[ald],min_t,max_t,min_h,max_h,min_v1,max_v1,min_v2,max_v2,min_t,max_t,min_h,max_h,min_v1,max_v1,min_v2,max_v2))
            prompt("Press any key to continue...")
            clearscreen()

        if option == "2" or option == "4":
            global cur
            cur.execute("""select * from alertables""")
            al = cur.fetchall()
            al = list(al)
            if al == []:
                print "No Alertables have been set."
            else:
                print "Alertables:"
                print "X ) Sensor: Temp (C) MIN/MAX , Humid MIN/MAX, v1 MIN/MAX, v2 MIN/MAX"
                l = 0
                for i in al:
                    print str(l), ") ", i[0],":",i[1],"/",i[2],",",i[3],"/",i[4],",",i[5],"/",i[6],",",i[7],"/",i[8]
                    l = l + 1
                if option == "4":
                    ald = -1
                    while ald == -1:
                        ald = prompt("Enter number of Alertable to be deleted: ")
                        try:
                            ald = int(ald)
                            if ald >= (len(al)):
                                ald = -1
                        except:
                            ald = -1
                    cur.execute("""delete from alertables where sid=%s""",(al[ald][0]))
                    print al[ald][0] + " has been deleted"

            prompt("Press any key to continue...")
            clearscreen()
    else:
        option = 0
        while option == 0:
            option = prompt("ADD, DEL, LIST, EXIT?  ")
            option = option.lower()
            options = ["add","del","list","exit","a","d","l","e"]
            if option not in options:
                option = 0
                clearscreen()
        if option == "add" or option == "a":
            sid = prompt("Sensor ID: ")
            min_t = prompt("Minimum Temperature (C), * for default: ")
            if min_t == "*":
                min_t = "5"
            max_t = prompt("Maximum Temperature (C), * for default: ")
            if max_t == "*":
                max_t = "35"
            min_h = prompt("Minimum Humidity, * for default: ")
            if min_h == "*":
                min_h = "10"                                        
            max_h = prompt("Maximum Humidity, * for default: ")
            if max_h == "*":
                max_h = "85"
            min_v1 = prompt("Minimum v1, * for default: ")
            if min_v1 == "*":
                min_v1 = "0"
            max_v1 = prompt("Maximum v1, * for default: ")
            if max_v1 == "*":
                max_v1 = "0"
            min_v2 = prompt("Minimum v2, * for default: ")
            if min_v2 == "*":
                min_v2 = "0"
            max_v2 = prompt("Maximum v2, * for default: ")
            if max_v2 == "*":
                max_v2 = "0"
            cur.execute("""insert ignore into alertables values(%s,%s,%s,%s,%s,%s,%s,%s,%s)""",(sid,min_t,max_t,min_h,max_h,min_v1,max_v1,min_v2,max_v2))
        if option == "del" or option == "d":
            sid = prompt("Sensor ID: ")
            cur.execute("""delete from alertables where sid=%s""",(sid))
        if option == "list" or option == "l":
            global cur
            cur.execute("""select * from alertables""")
            al = cur.fetchall()
            al = list(al)
            if al == []:
                print "None found."
            else:
                for i in al:
                    print i[0],":",i[1],"/",i[2],",",i[3],"/",i[4],",",i[5],"/",i[6],",",i[7],"/",i[8]
        if option == "exit" or option == "e":
            clearscreen()
            global ms
            try:
                ms.close()
                print "Connection to DB has been closed"
            except:
                pass
            print "Alertables Exiting"
            sys.exit(0)                
        
#toaddrs  = prompt("To: ").split()
#print "Enter message, end with ^D (Unix) or ^Z (Windows):"
#print type(toaddrs),toaddrs